<template>
	<view class="my-page">
		<!-- 用户信息 -->
		<view class="user-info">
			<view class="info">
				<text class="username" v-if="user">{{user.username}}</text><br>
				<text class="username" v-if="!user" @click="toLogin">前往登录</text>
				<text class="userid" v-if="user">ID: {{ user.userId }}</text><br>
				<text class="email" v-if="user">email: {{ user.email }}</text><br>
				<text class="createAt" v-if="user">createAt: {{ formatDate(user.createdAt) }}</text><br>
			</view>
		</view>
		
		<!-- 功能菜单 -->
		<view class="menu-list">
			<view class="menu-item" @click="switchPosts">
				<text>我的帖子</text>
			</view>
			<view class="menu-item" @click="switchFavorite">
				<text>我的收藏</text>
			</view>
			<view class="menu-item" @click="toChangePsw">
				<text>修改密码</text>
			</view>
			<view class="menu-item" @click="logout">
				<text>退出登录</text>
			</view>
			<view class="menu-item" @click="showConfirm('注销账号', '确定要注销账号吗？这将不可逆。')">
				<text>注销账号</text>
			</view>
		</view>
		<!-- 帖子列表 -->
		<view class="post-list" v-if="viewOption == 'posts'">
			<block v-if="posts.length > 0">
				<view class="post-item" v-for="(post, index) in posts" :key="index" @click="toPostDetail(post.postId)">
					<view class="post-title">{{ post.title }}</view>
					<view class="post-meta">
						<text>发表时间: {{ formatDate(post.createdAt) }}</text>
					</view>
					<view class="post-content">{{ post.content }}</view>
					<view class="post-actions">
						<view class="more-options" @click.stop="showPostMenu(post)">
							<text>...</text>
						</view>
					</view>
				</view>
			</block>
			<view v-else class="no-posts">暂无帖子</view>
		</view>
		<!-- 收藏列表 -->
		<view class="favorite-list" v-if="viewOption == 'favorites'">
			<block v-if="favorites.length > 0">
				<view class="favorite-item" v-for="(favorite, index) in favorites" :key="index" @click="toPostDetail(favorite.postId)">
					<view class="favorite-id">收藏ID: {{ favorite.favoriteId }}</view>
					<view class="favorite-meta">
						<text>收藏时间: {{ formatDate(favorite.createdAt) }}</text>
					</view>
					<view class="favorite-actions">
						<view class="more-options" @click.stop="showFavoriteMenu(favorite)">
							<text>...</text>
						</view>
					</view>
				</view>
			</block>
			<view v-else class="no-favorites">暂无收藏</view>
		</view>
		<!-- 加载更多 -->
		<uni-load-more :status="status" :icon-size="16" :content-text="contentText"></uni-load-more>
		<!-- 弹出菜单 -->
		<uni-popup ref="postMenuPopup" type="bottom">
			<view class="popup-menu">
				<button @click="editPost(selectedPost.postId)">编辑</button>
				<button @click="deletePost(selectedPost.postId)">删除</button>
			</view>
		</uni-popup>
		<uni-popup ref="favoriteMenuPopup" type="bottom">
			<view class="popup-menu">
				<button @click="cancelFavorite(selectedFavorite.favoriteId)">取消收藏</button>
			</view>
		</uni-popup>
	</view>
</template>


<script>
	export default {
		data() {
			return {
				user: {},
				token: '',
				viewOption: '',
				posts: [],
				favorites: [],
				pageNum: 1,
				pageSize: 6,
				totalPage: 0,
				status: "no-more",
				contentText: {
					contentdown: "上拉加载更多",
					contentrefresh: "正在加载",
					contentnomore:"没有更多数据"
				},
				selectedPost: null,
				selectedFavorite: null,
			}
		},
		onLoad() {
			this.user = uni.getStorageSync("user");
			console.log("user:",this.user);
			this.token = uni.getStorageSync("token");
			this.viewOption = 'posts';
			this.getPosts();
			this.getPostTotalPage();
		},
		onShow() {
			if (this.token) {
				uni.request({
					url: 'http://localhost:8080/checkTokenStatus',
					method: 'POST',
					header: {
						'Authorization': this.token
					},
					success: res => {
						if (res.data.success == false) {
							uni.removeStorageSync("token");
							uni.removeStorageSync("user");
							uni.showToast({
								icon: "none",
								title: "登录已过期"
							})
							this.toLogin();
						}
					},
					fail: () => {},
					complete: () => {}
				});
			}
		},
		onPullDownRefresh() {
			console.log("下拉刷新");
			this.posts = [];
			this.favorites = [];
			this.pageNum = 1;
			this.getPosts();
		},
		onReachBottom() {
			console.log("上拉触底");
			if(this.pageNum > this.totalPage) {
				uni.showToast({
					icon: "none",
					title: '没有下一页数据了'
				});
				this.status = "no-more"
			} else {
				console.log("有下一页数据");
				this.pageNum++;
				this.getPosts();
			}
		},
		methods: {
			toLogin() {
				uni.navigateTo({
					url: '/pages/login/login',
				});
			},
			formatDate(date) {
				const options = {
					year: 'numeric',
					month: 'long',
					day: 'numeric',
					hour: '2-digit',
					minute: '2-digit',
					hour12: false
				};
				return new Date(date).toLocaleDateString(undefined, options);
			},
			switchPosts() {
				this.favorites = [];
				this.viewOption = "posts";
				this.getPosts();
				this.getPostTotalPage();
			},
			switchFavorite() {
				this.posts = [];
				this.viewOption = "favorites"
				this.getPosts();
				this.getPostTotalPage();
			},
			toChangePsw() {
				uni.navigateTo({
					url: '/pages/changePsw/changePsw'
				});
			},
			showPostMenu(post) {
				this.selectedPost = post;
				this.$refs.postMenuPopup.open();
			},
			showFavoriteMenu(favorite) {
				this.selectedFavorite = favorite;
				this.$refs.favoriteMenuPopup.open();
			},
			editPost(id) {
				uni.navigateTo({
					url: '/pages/editPost/editPost?id=' + id,
				});
			},
			deletePost(id) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除此帖子吗？',
					success: async (res) => {
						if (res.confirm) {
							this.sendDeleteRequest(id);
						}
					}
				});
			},
			sendDeleteRequest(id) {
				const token = this.token;
				if(!token) {
					uni.showToast({
						icon: "none",
						title: '请先登录'
					});
					return;
				}
				uni.request({
					url: "http://localhost:8080/deletePost",
					method: "POST",
					data: {
						postId: id
					},
					header: {
						'Authorization':token,
						'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
					},
					success: (res) => {
						if (res.data.code == 200) {
							uni.showToast({
								icon: "none",
								title: '删除成功'
							});
							this.getPosts();
						}
						else {
							uni.showToast({
								icon: "none",
								title: "删除失败，请稍后再试"
							});
						}
					},
					fail: () => {
						uni.showToast({
							icon: "none",
							title: "网络错误"
						});
					},
				});
			},
			cancelFavorite(id) {
				uni.showModal({
					title: '确认取消收藏',
					content: '确定要取消收藏此帖子吗？',
					success: async (res) => {
						if (res.confirm) {
							console.log("favorite:",id);
							this.sendCancelFavoriteRequest(id);
						}
					}
				});
			},
			sendCancelFavoriteRequest(id) {
				console.log("id:",id);
				const token = this.token;
				if(!token) {
					uni.showToast({
						icon: "none",
						title: '请先登录'
					});
					return;
				}
				uni.request({
					url: "http://localhost:8080/removeFavorite",
					method: "POST",
					data: {
						favoriteId:id
					},
					header: {
						'Authorization':token,
						'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
						
					},
					success: (res) => {
						console.log(res.data);
						if (res.data.code == 200) {
							uni.showToast({
								icon: "none",
								title: '取消收藏成功'
							});
							this.getPosts();
						}
						 else {
							uni.showToast({
								icon: "none",
								title: "取消收藏失败，请稍后再试"
							});
						}
					},
					fail: () => {
						uni.showToast({
							icon: "none",
							title: "网络错误"
						});
					},
				});
			},
			getPosts() {
				this.status = '正在加载';
				const token = this.token;
				var curUrl = '';
				if(!token) {
					uni.showToast({
						icon: "none",
						title: "请先登录",
					});
					return;
				}
				if(this.viewOption == 'posts') {
					curUrl = "http://localhost:8080/getMyPostList"
				}
				if(this.viewOption == 'favorites') {
					curUrl = "http://localhost:8080/getFavoriteList"
				}
				uni.request({
					url: curUrl,
					method: "GET",
					data: {
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						userId: this.user.userId
					},
					header: {
						'Authorization':token
					},
					success: (res) => {
						uni.stopPullDownRefresh();
						if(this.viewOption == 'posts') {
							this.posts = res.data.data.records;
							console.log("posts:",this.posts);
						}
						if(this.viewOption == 'favorites') {
							this.favorites = res.data.data.records;
						}
					},
					fail: () => {
						uni.showToast({
							icon: "none",
							title: "网络错误"
						});
					},
				});
			},
			getPostTotalPage() {
				this.status = '正在加载';
				const token = this.token;
				var curUrl = '';
				if(!token) {
					uni.showToast({
						icon: "none",
						title: '请先登录'
					});
					return;
				}
				if(this.viewOption == 'posts') {
					curUrl = "http://localhost:8080/getMyPostTotalPage"
				}
				if(this.viewOption == 'favorites') {
					curUrl = "http://localhost:8080/getFavoriteTotalPage"
				}
				uni.request({
					url: curUrl,
					method: "GET",
					data: {
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						userId: this.user.userId
					},
					header: {
						'Authorization':token
					},
					success: (res) => {
						console.log("res.data:",res.data);
						console.log("res.data.data.pages:",res.data.data.pages);
						this.totalPage = res.data.data.pages + 1;
					},
					fail: () => {},
					complete: () => {}
				});
			},
			toPostDetail(id) {
				uni.navigateTo({
					url: '/pages/detail/detail?id=' + id,
				});
			},
			logout() {
				this.viewOption = "logout";
				uni.removeStorageSync("token");
				uni.removeStorageSync("user");
				uni.reLaunch({
					url: "/pages/me/me"
				})
			},
			showConfirm(title, content) {
				uni.showModal({
					title,
					content,
					success: (res) => {
						if (res.confirm) {
							this.handleAccountDeletion();
						}
					}
				});
			},
			handleAccountDeletion() {
				const token = this.token;
				if(!token) {
					uni.showToast({
						icon: "none",
						title: '请先登录'
					});
					return;
				}
				uni.request({
					url: "http://localhost:8080/deleteAccount",
					method: "POST",
					header: {
						'Authorization':token,
						'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
					},
					data: {
						userId: this.user.userId
					},
					success: (res) => {
						if (res.data.code == 200) {
							uni.showToast({
								icon: "success",
								title: "账号已成功注销"
							});
							this.logout(); // 注销后自动登出
						} else {
							uni.showToast({
								icon: "none",
								title: "注销失败，请稍后再试"
							});
						}
					},
					fail: () => {
						uni.showToast({
							icon: "none",
							title: "网络错误"
						});
					}
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	.my-page {
		background-color: #f7f7f7;
		padding-top: 20rpx;

		.user-info {
			display: flex;
			align-items: center;
			padding: 30rpx;
			background-color: white;
			margin-bottom: 20rpx;

			.info {
				flex-grow: 1;

				.username {
					font-size: 36rpx;
					font-weight: bold;
				}

				.userid,
				.email,
				.createAt {
					font-size: 28rpx;
					color: #999;
				}
			}
		}

		.menu-list {
			background-color: white;
			padding: 20rpx;

			.menu-item {
				padding: 20rpx;
				border-bottom: 1px solid #ddd;
				text-align: left;
				font-size: 30rpx;
				color: #333;

				&:last-child {
					border-bottom: none;
				}
			}
		}
		
		.favorite-list,
		.post-list {
			background-color: white;
			padding: 20rpx;
	
			.favorite-item,
			.post-item {
				padding: 20rpx;
				margin-bottom: 20rpx;
				background-color: #fff;
				border-radius: 10rpx;
				box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	
				.favorite-id,
				.post-title {
					font-size: 36rpx;
					font-weight: bold;
					margin-bottom: 10rpx;
				}
	
				.post-content {
					font-size: 30rpx;
					color: #666;
					margin-bottom: 10rpx;
					white-space: pre-line;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 3;
					-webkit-box-orient: vertical;
				}
	
				.favorite-meta,
				.post-meta {
					font-size: 24rpx;
					color: #999;
				}
			}
	
			.no-favorites,
			.no-posts {
				text-align: center;
				padding: 20rpx;
				color: #ccc;
			}
		}
		
		.post-actions,
		.favorite-actions {
			display: flex;
			justify-content: flex-end;
			align-items: center;
	
			.more-options {
				text-align: right;
				font-size: 28rpx;
				color: #999;
			}
		}
	
		.popup-menu {
			width: 100%;
			padding: 20rpx;
			background-color: white;
	
			button {
				width: 100%;
				margin-bottom: 20rpx;
				background-color: #1296db;
				color: white;
				border: none;
				padding: 10rpx 20rpx;
				border-radius: 5rpx;
			}
		}
	}
</style>